import com.phidgets.AccelerometerPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.AccelerationChangeEvent;
import com.phidgets.event.AccelerationChangeListener;

public class AccelerometerController
{
	private AccelerometerPhidget acc1 = null;
	private AccelerometerPhidget acc2 = null;
	private AccelerometerPhidget acc3 = null;
	private State state;
	private PillarController pc;
	
	public AccelerometerController(State state, PillarController pc)
	{
		this.state = state;
		this.pc = pc;
	}
	
	public void startProgram()
	{
		try
		{
			acc1 = new AccelerometerPhidget();
			acc2 = new AccelerometerPhidget();
			acc3 = new AccelerometerPhidget();
			acc1.open(158320);
			acc1.addAccelerationChangeListener(addACL(acc1, 158320, 1));
			
			acc2.open(159411);
			acc2.addAccelerationChangeListener(addACL(acc2, 159411, 2));
			
			acc3.open(159477);
			acc3.addAccelerationChangeListener(addACL(acc3, 159477, 3));
		} 
		catch (PhidgetException e) 
		{
			System.out.println("Error");
			e.printStackTrace();
		}
	}
	
	public void endProgram()
	{
		try
		{
			acc1.close();
			acc2.close();
			acc3.close();
		}
		catch (PhidgetException pe) 
		{
			System.out.println("PhidgetCloseProgramException");
		}
	}
	
	public synchronized AccelerationChangeListener addACL(final AccelerometerPhidget acc, final int serialNumber, final int thisPillar)
	{
		return new AccelerationChangeListener()
		{
			double i = 0.5;
			public void accelerationChanged(AccelerationChangeEvent ae) 
			{
				try 
				{
					if (ae.getValue() > i + 1.65 || ae.getValue() < i - 1.65)
					{
						if (acc.getSerialNumber() == serialNumber && state.getCurrentPillar() == thisPillar)
						{
							state.setIsHit(true);
							pc.pillarHit();
						}
					}
				} 
				catch (PhidgetException e) 
				{
				}
			}
		};
	}
}